package com.yeyi.ytest.java8.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;

public class StreamToList {
	public static void main(String[] args) {
		stringToList();
	}
	
	void test(){
		List<Student> students = new ArrayList<Student>();
		students.add(new Student("11",1L));
		students.add(new Student("22",2L));
		students.add(new Student("33",null));
		
		// 拼接成 ID 列表
		// 注意 getId==null 的情况会报异常,但没有元素的 students 没问题
//		List<Long> ids = students.stream().map(Student::getId).collect(Collectors.toList());
//		System.out.println(ids);
//		List<Long> ids2 = students.stream().map(Student::getId).distinct().collect(Collectors.toList()); // 多了去重复
//		System.out.println(ids2);
		//                                  过滤 null==getId
		//                                                             过滤 getId 重复的项
		//                                                                                            转成 List 返回
		List<Long> ids3 = students.stream().filter(e->e.getId()!=null).map(Student::getId).distinct().collect(Collectors.toList());
		System.out.println(ids3);
		
		// 去重复
		List<String> unique = Lists.newArrayList("1","2","1").stream().distinct().collect(Collectors.toList());
		System.out.println(unique);
	}
	
	/**
	 * 逗号分隔转 list
	 */
	public static void stringToList() {
		//You can use the Lambda functions of Java 8 to achieve this without looping
		//来自：http://stackoverflow.com/questions/19946980/convert-string-to-listlong
		 
		String ids= "1,2,3,4,5,6";
		List<Long> listIds = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		System.out.println(Arrays.toString(listIds .toArray()));//[1,2,3,3,4,5,6]
	}
}

class Student{
	private String name;
	private Long id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public Student(String name, Long id) {
		super();
		this.name = name;
		this.id = id;
	}
}